package com.neuedu.controller;

import com.neuedu.bean.DeliveryAddress;
import com.neuedu.common.R;
import com.neuedu.service.DeliveryAddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
// 2. 设置该模块的请求路径，如/user
@RequestMapping("/address")
// 3. 解决跨域
@CrossOrigin
public class DeliveryAddressController {

    @Autowired
    private DeliveryAddressService deliveryAddressService;

    @GetMapping("/listDeliveryAddressByUserId/{userId}")
    public R listDeliveryAddressByUserId(@PathVariable("userId") String userId) {

        List<DeliveryAddress> deliveryAddresses = deliveryAddressService.listDeliveryAddressByUserId(userId);

        return R.ok().data(deliveryAddresses);
    }

    @PostMapping("/removeDeliveryAddress")
    public R removeDeliveryAddress(Integer daId) {
        try {
            int i = deliveryAddressService.removeDeliveryAddress(daId);
            return R.ok().data(i);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @PostMapping("/updateDeliveryAddress")
    public R updateDeliveryAddress(DeliveryAddress deliveryAddress) {
        try {
            deliveryAddressService.updateDeliveryAddress(deliveryAddress);
            return R.ok().data(1);
        } catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    @PostMapping("/saveDeliveryAddress")
    public R saveDeliveryAddress(DeliveryAddress deliveryAddress) {
        try {
            int i = deliveryAddressService.saveDeliveryAddress(deliveryAddress);
            if (i>0) {
                return R.ok().msg("地址保存成功");
            }
        } catch (Exception e) {           // 捕获所有异常，防止系统崩溃
            throw new RuntimeException(e);
        }
        return R.error().msg("地址信息保存失败！");
    }

    @GetMapping("/getDeliveryAddressById/{daId}")
    public R getDeliveryAddressById(@PathVariable("daId") Integer adId) {
        try {
            DeliveryAddress deliveryAddress = deliveryAddressService.getDeliveryAddressById(adId);
            return R.ok().data(deliveryAddress);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
